package drds.plus.executor.function.scalar.operator;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.sql_process.type.Calculator;
import drds.plus.sql_process.type.Type;
import drds.plus.sql_process.type.impl.DateType;
import drds.plus.sql_process.type.impl.IntervalType;
import drds.plus.sql_process.type.impl.TimestampType;

/**
 * @since 5.0.0
 */
public class Sub extends ScalarFunction {

    public Object compute(ExecuteContext executeContext, Object[] args) {
        Type type = this.getReturnType();
        Calculator cal = type.getCalculator();
        // 如果加法中有出现IntervalType类型，转到时间函数的加法处理
        for (Object arg : args) {
            if (arg instanceof IntervalType && !(type instanceof TimestampType || type instanceof DateType)) {
                cal = Type.TimestampType.getCalculator();
            }
        }

        if (type.getCalculator() != cal) {
            return type.convert(cal.sub(args[0], args[1]));
        } else {
            return cal.sub(args[0], args[1]);
        }
    }

    public Type getReturnType() {
        Object arg0 = function.getArgList().get(0);
        Object arg1 = function.getArgList().get(1);
        // 比如出现"2012-12-10" - interval_primary 1 DAY
        // interval不会出现在第一位参数
        if (getType(arg1) instanceof IntervalType) {
            return getType(arg0);
        }

        return getArgListTypeAndUseLongTypeWhenOccureNonNumberType();
    }

    public String[] getFunctionNames() {
        return new String[]{"sub", "-"};
    }
}
